<?php
namespace haibao\app\business;

use haibao\app\data\AppUpdate as AppUpdateData;
use haibao\app\data\ImageLibrary as ImageLibraryData;

class AppUpdate extends Base{
    
    public static function getAppUpdateList($filter){
        $appUpdateData = new AppUpdateData();
        return $appUpdateData->getAppUpdateList($filter);
    }
    
    public static function changeStatus($id, $status,$appType,$version){
        if($status == \haibao\app\model\data\AppUpdate::STATUS_DELETE){
            self::checkOperation(self::FUNC_CODE_APP_UPDATE_DELETE);
        }
        $appUpdateData = new AppUpdateData();
        $appUpdateData->changeStatus($id, $status,$appType,$version);
        if($status == \haibao\app\model\data\AppUpdate::STATUS_DELETE){
            self::saveOperateHistory(self::FUNC_CODE_APP_UPDATE_DELETE, array('id'=>$id,'status'=>$status));
        }
    }
    
    public static function getUpdateById($id){
        $appUpdateData = new AppUpdateData();
        return $appUpdateData->getUpdateById($id);
    }
    
    public static function getOneUpdate($version,$appType){
        $appUpdateData = new AppUpdateData();
        return $appUpdateData->getOneUpdate($version,$appType);
    }
    
    public static function saveUpdate($model){
        $imageLibraryModel = new \haibao\app\model\data\ImageLibrary();
        $model->CreateBy = self::getCurrentUser()->Id;
        $model->CreateTime = new \DateTime();
        
        if(!$model->Id){
           $repeatResult = self::getOneUpdate($model->Version, $model->AppType);
           if($repeatResult){
               throw new BusinessException('版本号和平台重复');
           }
           $model->CreateBy = self::getCurrentUser()->Id;
           $model->CreateTime = new \DateTime();
           $model->Status = \haibao\app\model\data\AppUpdate::STATUS_DISABLE;
        }else {
            $versionInfo = self::getUpdateById($model->Id);
            $model->CreateBy = $versionInfo->CreateBy;
            $model->CreateTime = $versionInfo->CreateTime;
            $model->Status = $versionInfo->Status;
        }
        $appUpdateData = new AppUpdateData();
        return $appUpdateData->saveUpdate($model);
    }
    
    public static function getUpdateByAppType($appType,$appVersion){
        if(!$appType || !$appVersion){
            throw new BusinessException('参数不正确', \haibao\app\business\Base::DATA_ERROR_CODE_EMPTY);
        }
        if($appType != \haibao\app\model\data\PhoneInfo::OS_TYPE_ANDROID && $appType != \haibao\app\model\data\PhoneInfo::OS_TYPE_IOS){
            throw new BusinessException('参数不正确', \haibao\app\business\Base::DATA_ERROR_CODE_EMPTY);
        }
        $appUpdateData = new AppUpdateData();
        return $appUpdateData->getUpdateByAppType($appType,$appVersion);
    }
    
}